package com.tanguy.user.net.http.json;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.tanguy.user.Const;
import com.tanguy.user.net.http.HttpManager;
import com.tanguy.user.utlis.extend.FunctionKt;

import java.io.IOException;
import java.lang.reflect.Type;

import cn.sinata.xldutils_kotlin.data.ResultData;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by liaoxiang on 16/6/21.
 */
public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson mGson;//gson对象
    private final TypeAdapter<T> adapter;
    private static final String TAG = "JsonResponseBodyConvert";

    /**
     * 构造器
     */
    public JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.mGson = gson;
        this.adapter = adapter;
    }

    /**
     * 转换
     *
     * @param responseBody
     * @return
     * @throws IOException
     */
    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        String s = responseBody.string();
        //如果返还值需解密
        if (HttpManager.INSTANCE.getDecodeDes()) {
            Type type = new TypeToken<ResultData<String>>() {
            }.getType();
            ResultData<String> data = mGson.fromJson(s, type);
            String newData = data.getDecodeDesString();
            Log.e(TAG, "convert: \n" + newData);
            System.err.println(newData);
            return adapter.fromJson(newData);
        }

//        JsonReader jsonReader = mGson.newJsonReader(responseBody.charStream());
        try {
            if (Const.DEBUG.RESPONSE)
                FunctionKt.loge(s, 2, "tanguy_loge");
            return adapter.fromJson(s);
//            return adapter.read(jsonReader);
        } finally {
            responseBody.close();
        }
    }
}
